package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.OrderItemMapper;
import com.jt.mapper.OrderMapper;
import com.jt.mapper.OrderShippingMapper;
import com.jt.pojo.Order;
import com.jt.pojo.OrderItem;
import com.jt.pojo.OrderShipping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrderServiceImpl implements DubboOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderShippingMapper orderShippingMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;


    @Override
    @Transactional
    public String saveOrder(Order order) {

        //1.准备订单ID号
        String orderId = "" + order.getUserId() + System.currentTimeMillis();

        //2.订单入库
        order.setOrderId(orderId).setStatus(1);
        orderMapper.insert(order);

        //3.完成订单物流入库
        OrderShipping orderShipping = order.getOrderShipping();
        orderShipping.setOrderId(orderId);
        orderShippingMapper.insert(orderShipping);

        //4.完成订单商品入库操作
        List<OrderItem> orderItems = order.getOrderItems();
        //手动完成批量赋值的操作
        //insert into

        orderItemMapper.insertObjects(orderId, orderItems);

//		for(OrderItem orderItem : orderItems){
//			orderItem.setOrderId(orderId);
//			orderItemMapper.insert(orderItem);
//		}

        return orderId;
    }

    @Override
    public Order findOrderById(String id) {
        Order order = orderMapper.selectById(id);
        OrderShipping orderShipping = orderShippingMapper.selectById(id);
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", id);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);
        return order.setOrderShipping(orderShipping).setOrderItems(orderItems);
    }
}
